package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {

    @Autowired
    private CheckGroupDao checkGroupDao;
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {

        checkGroupDao.add(checkGroup);
        this.setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

    }

    public void setCheckGroupAndCheckItem(Integer checkGroupId,Integer[] checkitemIds){
        if(checkGroupId!=null && checkitemIds.length>0){
                //checkgroupId与checkitemId的值与checkgroupDao中的值要一致
             for (Integer checkitemId:checkitemIds){
                 Map<String, Integer> mp = new HashMap<>();  //不太懂
                 mp.put("checkgroupId",checkGroupId);
                 mp.put("checkitemId",checkitemId);
                 checkGroupDao.setCheckGroupAndCheckItem(mp);
             }
        }
    }

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);

        Page<CheckGroup> page = checkGroupDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<CheckGroup> result = page.getResult();
        return new PageResult(total,result);
    }

    @Override
    public void del(Integer id) {
        //判断中间表是否有数据
        checkGroupDao.deleteAssociation(id);
        checkGroupDao.delete(id);
    }

    @Override
    public CheckGroup findById(Integer id) {

        //根据检查组id删除中间表数据（清理原有关联关系）

        return checkGroupDao.findById(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {

        //判断中间表是否有数据
        checkGroupDao.deleteAssociation(checkGroup.getId());

        setCheckGroupAndCheckItem(checkGroup.getId(),checkitemIds);

        checkGroupDao.edit(checkGroup);
    }

    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {

        List<Integer> checkItemIdsByCheckGroupId = checkGroupDao.findCheckItemIdsByCheckGroupId(id);
        return checkItemIdsByCheckGroupId;
    }

    @Override
    public List<CheckGroup> findAlls() {
        List<CheckGroup> alls = checkGroupDao.findAlls();
        return alls;
    }


}
